﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Crm2011.Framework.Core;



namespace ScriptEase
{
    /// <summary>
    /// 
    /// </summary>
    public class UserDataList
    {
        public static readonly UserDataList Current = new UserDataList("ScriptEase.UserData.xml");


        private readonly List<UserData> _list;
        private readonly string _fileName;
        private const int MaxItemCount = 16;



        private UserDataList(string listName)
        {
            _fileName = PublicFunc.GetFullFilePath(@"%AppData%\Schmidt e-Services GmbH\" + listName, null, false);
            _list = File.Exists(_fileName) ? SerializationHelper.Deserialize<List<UserData>>(File.ReadAllText(_fileName)) : new List<UserData>();
        }


        /// <summary>
        /// Gets the specified item by its Id.
        /// </summary>
        /// <remarks>
        /// If the item exists it is returned. 
        /// If it does not exist a new item with the requested Id is created and returned.
        /// It is important to notice that the new item is not yet part of the list.
        /// </remarks>
        public UserData Get(Guid itemId)
        {
            return _list.FirstOrDefault(ud => ud.ConnectionId == itemId) ?? new UserData { ConnectionId = itemId };
        }


        /// <summary>
        /// NewItem an new or existing item to the list and save the list.
        /// </summary>
        /// <remarks>
        /// Whe the item already exists it is move to the top of 
        /// the list (to become the most recent item).<br/>
        /// If the list is longer than <see cref="MaxItemCount"/> the list 
        /// is truncated to this limit. In any case the list is saved to disc 
        /// after this operation
        /// </remarks>
        /// <returns>
        /// true when a new profilel was added.<br/>
        /// false in case of an existing profile.</returns>
        public bool Set(UserData item)
        {
            var existingItem = _list.FirstOrDefault(i => i.ConnectionId == item.ConnectionId);
            if (existingItem != null)
                _list.Remove(existingItem); // remove to be inserted on top

            if (_list.Count == MaxItemCount)
                _list.Remove(_list[MaxItemCount - 1]);

            _list.Insert(0, item);
            saveToDisc();
            return (existingItem == null);
        }




        public void Delete(Guid itemId)
        {
            var existingItem = _list.FirstOrDefault(i => i.ConnectionId == itemId);
            if (existingItem == null) return;

            _list.Remove(existingItem);
            saveToDisc();
        }



        private void saveToDisc()
        {
            string directoryName = Path.GetDirectoryName(_fileName);
            if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);
            File.WriteAllText(_fileName, SerializationHelper.Serialize(_list));
        }
    }
}